import { pages, subPackages } from '@/pages.json'

const getAllPages = () => {
	const mainPages = pages.map(page => `/${page.path}`)
	
	const subPages = subPackages.reduce<string[]>((ret, cur) => {
		const paths = cur.pages.map(page => `/${cur.root}/${page.path}`)
		
		return [...ret, ...paths]
	}, [])
	
	return [...mainPages, ...subPages]
}

let allPages: string[] = []
const notFoundPage = '/pages/notfound/notfound'

const navigateInterceptor: UniApp.InterceptorOptions = {
	invoke: (options) => {
		if (allPages.length === 0) {
			allPages = getAllPages()
		}
		
		const path = options.url.split('?')[0]
		
		if (!allPages.includes(path)) {
			console.log('路由不存在')
			options.url = notFoundPage
		}
	}
}

export function createRouterInterceptor() {
	uni.addInterceptor('navigateTo', navigateInterceptor)
}
